// import necessary icons and components
import { login } from '@/services/demo/login';
import { loginBySms } from '@/services/demo/loginBySms';
import { smsCaptcha } from '@/services/demo/smsCaptcha';
import {
  LockOutlined,
  MailOutlined,
  SafetyCertificateOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { Button, Checkbox, Col, Form, Input, Row, Tabs, message } from 'antd';
import { useEffect, useState } from 'react';
import { Link } from 'umi';
import './index.less';

const { TabPane } = Tabs;

const LoginPager = () => {
  const [activeTabKey, setActiveTabKey] = useState('username'); // 初始默认选中的tab
  const [form] = Form.useForm();
  const [captchaSrc, setCaptchaSrc] = useState('/api/user/kaptcha');

  useEffect(() => {
    // 页面加载时请求验证码
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    refreshCaptcha();
  }, []);

  const handleTabChange = (key:any) => {
    setActiveTabKey(key);
  };

  const onFinish1 = async (value:any) => {
    // console.log(value.userName + '密码' + value.password);
    try {
      const res = await login(value.userName, value.password, value.code);
      console.log('@@@',res)
      if (res.code===0) {
        // 处理登录成功后的逻辑，比如跳转页面等
        console.log('Login successful:', res.data);
        window.location.href = '/table';
      } else {
        console.log('Login failed');
      }
    } catch (error) {
      console.error('Login failed:', error);
      // 处理登录失败的逻辑
      console.log(value);
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      refreshCaptcha(); // 登录失败后刷新验证码
    }
  };

  // 邮箱登录
  const onFinish = async (value:any) => {
    // console.log(value.email + '验证码' + value.code);
    try {
      const res = await loginBySms(value.email, value.code);
      console.log('aaaa',res)
      if (res.code===0) {
        console.log('Login successful:', res.data);
        window.location.href = '/table';
        // 处理登录成功后的逻辑，比如跳转页面等
      } else {
        console.log('Login failed'); //你运行
      }
    } catch (error) {
      console.error('Login failed:', error);
      // 处理登录失败的逻辑
      console.log(value);
    }
  };

  // 邮箱验证码
  const code1 = async () => {
    const email = form.getFieldValue('email');
    if (!email) {
      message.error('请输入邮箱!');
      return;
    }

    console.log(email + '邮箱');
    try {
      const res = await smsCaptcha(email);
      console.log('邮箱' + email);
      if (res.code === 0) {
        // 处理发送成功后的逻辑
        console.log('发送成功', res);
        message.success('验证码已发送成功！');

      } else {
        console.log('发送失败');
        message.error('验证码已发送失败！');
      }
    } catch (error) {
      console.error('发送失败', error);
      // 处理发送失败的逻辑
      console.log(email);
    }
  };

  const refreshCaptcha = () => {
    // 重新请求验证码
    setCaptchaSrc(`http://localhost:8082/api/user/kaptcha?${Date.now()}`);
  };

  return (
      <div className="box1">
        <h1 className="text" style={{ marginTop: 20, marginLeft: 55 }}>
          数字马力，欢迎您
        </h1>

        <Tabs
            activeKey={activeTabKey}
            onChange={handleTabChange}
            style={{ marginTop: 10, marginLeft: 40, marginRight: 40 }}
        >
          <TabPane tab="用户名登录" key="username">
            <Form
                form={form}
                name="normal_login"
                initialValues={{ remember: true }}
                onFinish={onFinish1}
                style={{ maxWidth: 300 }}
                action="/table"
                method="post"
            >
              <Form.Item
                  name="userName"
                  rules={[{ required: true, message: '请输入用户名!' }]}
              >
                <Input prefix={<UserOutlined />} placeholder="用户名" />
              </Form.Item>
              <Form.Item
                  name="password"
                  rules={[{ required: true, message: '请输入密码!' }]}
              >
                <Input.Password
                    prefix={<LockOutlined />}
                    placeholder="密码"
                    visibilityToggle
                />
              </Form.Item>
              <Form.Item
                  name="code"
                  rules={[{ required: true, message: '请输入图形验证码!' }]}
              >
                <Row gutter={8}>
                  <Col span={16}>
                    <Input
                        prefix={<SafetyCertificateOutlined />}
                        placeholder="图形验证码"
                    />
                  </Col>
                  <Col span={8}>
                    <img
                        src={captchaSrc}
                        alt="captcha"
                        style={{ cursor: 'pointer', width: '100%' }}
                        onClick={refreshCaptcha}
                    />
                  </Col>
                </Row>
              </Form.Item>
              <Form.Item>
                <Checkbox defaultChecked={true}>自动登录</Checkbox>
                <Link to="/reset">忘记密码</Link>
                <Link
                    to="/register"
                    style={{
                      float: 'right',
                    }}
                >
                  新用户注册
                </Link>
              </Form.Item>
              <Form.Item>
                <Button
                    type="primary"
                    htmlType="submit"
                    style={{ width: '100%' }}
                >
                  登录
                </Button>
              </Form.Item>
            </Form>
          </TabPane>

          {/* 邮箱登录tab */}
          <TabPane tab="邮箱登录" key="email">
            <Form
                form={form}
                name="normal_login"
                initialValues={{ remember: true }}
                onFinish={onFinish}
                style={{ maxWidth: 300 }}
            >
              <Form.Item
                  name="email"
                  rules={[
                    { required: true, message: '请输入邮箱!' },
                    {
                      pattern:
                          /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
                      message: '邮箱格式错误！',
                    },
                  ]}
              >
                <Input prefix={<MailOutlined />} placeholder="邮箱" />
              </Form.Item>
              <Form.Item
                  name="code"
                  rules={[{ required: true, message: '请输入邮箱验证码!' }]}
              >
                <Row gutter={8}>
                  <Col span={16}>
                    <Input
                        prefix={<SafetyCertificateOutlined />}
                        placeholder="邮箱验证码"
                    />
                  </Col>
                  <Col span={8}>
                    <Button onClick={code1}>获取验证码</Button>
                  </Col>
                </Row>
              </Form.Item>
              <Form.Item>
                <Checkbox defaultChecked={true}>自动登录</Checkbox>
                <Link to="/reset">忘记密码</Link>
                <Link
                    to="/register"
                    style={{
                      float: 'right',
                    }}
                >
                  新用户注册
                </Link>
              </Form.Item>
              <Form.Item>
                <Button
                    type="primary"
                    htmlType="submit"
                    style={{ width: '100%' }}
                >
                  登录
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
        </Tabs>
      </div>
  );
};

export default LoginPager;
